package com.google.code.opengw.server.domain;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.google.code.opengw.support.OpenGWException;
import com.google.code.opengw.support.OpenGWLogger;


public class HTTPListener implements Runnable{

	private final Domain domain;
	private final ConnectionQueue connectionQueue;
	private ServerSocket serverSocket;
	private boolean systemActive;
	private boolean listenerAlive;
	
	public HTTPListener(Domain domain, ConnectionQueue connectionQueue){
		this.domain = domain;
		this.connectionQueue = connectionQueue;
		listenerAlive = false;
		systemActive = true;
	}
	
	@Override
	public void run() {
		listenerAlive = true;
		try {
			serverSocket = new ServerSocket(domain.getPort());
			while (systemActive) {
				Socket socket = serverSocket.accept();
				try {
					connectionQueue.addConnection(socket);
				} catch (OpenGWException e) {
					OpenGWLogger.addError(this.getClass(), e.getMessage(), e);
					try {
						Thread.sleep(100);
					} catch (Exception ex) {
					}
				}
			}
		} catch (Exception e) {
			OpenGWLogger.addError(this.getClass(), e.getMessage(), e);
		} finally {
			listenerAlive = false;
		}
	}
	
	public boolean isListenerAlive(){
		return listenerAlive;
	}
	
	public void setSystemActive(boolean systemActive) {
		this.systemActive = systemActive;
	}
	
	protected void closeServer() throws IOException {
		serverSocket.close();
	}

}
